﻿using System;
using System.Windows;
using System.Windows.Interactivity;

namespace FamilyBook.UI.WPF.Interaction
{
    public class PopupDialogInteractionAction : TriggerAction<FrameworkElement>
    {
        public static readonly DependencyProperty DialogViewProperty = DependencyProperty.Register("DialogView", 
            typeof(FrameworkElement),
            typeof(PopupDialogInteractionAction),
            new PropertyMetadata(null));

        public FrameworkElement DialogView
        {
            get { return (FrameworkElement)GetValue(DialogViewProperty); }
            set { SetValue(DialogViewProperty, value); }
        }

        protected override void Invoke(object parameter)
        {
            var args = (DetailsInteractionRequestEventArgs)parameter;

            if (DialogView == null)
                return;

            this.DialogView.DataContext = args.ViewModel;
            var dlgWnd = new Window()
                             {
                                 Owner = Window.GetWindow(this.AssociatedObject),
                                 Content = DialogView,
                                 WindowStartupLocation = WindowStartupLocation.CenterOwner,
                                 SizeToContent = SizeToContent.WidthAndHeight
                             };

            EventHandler viewCompleted = (sender, eventArgs) => dlgWnd.Close();
            args.ViewModel.ViewCompleted += viewCompleted;

            dlgWnd.ShowDialog();
            args.ViewModel.ViewCompleted -= viewCompleted;
            args.Callback();
        }
    }
}
